% Purpose: Calculate texture measurementA from Veggie Vision
% Date: 11/18/2012
% Author: R. Dutka
function [output] = Run_MeasurementA(mask, colorBand)
%Cross bar masks
[rows columns] = size(mask);
R = zeros(rows*columns, 2);
index = 1;
for a=1:rows
   for b=1:columns
    if mask(a, b) == 1
        R(index,:) = [a, b];
        index = index + 1;
    end
   end
end
%concat matrix (remove zeros)
R( ~any(R,2), : ) = [];
mx1 = [-1 2 -1];
my1 = reshape(mx1, 3, 1);
mx2 = [-1 -1 2 2 -1 -1];
my2 = reshape(mx2, 6, 1);
% apply masks
% nxr: number of im rows, etc.
[nxr, nxc] = size(colorBand);
[nmr, nmc] = size(mx1);
% get valid output region
nyr = nxr - nmr + 1;
nyc = nxc - nmc + 1;
% allocate output array
%y1 = zeros(nyr, nyc);
%y2 = zeros(nyr, nyc);
% convert from int8 to double
%y1 = double(y1);
%y2 = double(y2);
% run 2-D convolution for first cross bar mask
y1 = conv2(double(colorBand), double(mx1), 'same');
y2 = conv2(double(colorBand), double(my1), 'same');
% allocate output array
%y3 = zeros(nyr, nyc);
%y4 = zeros(nyr, nyc);
% convert from int8 to double
%y3 = double(y3);
%y4 = double(y4);
% run 2-D convolution for second cross bar mask
y3 = conv2(double(colorBand), double(mx2), 'same');
y4 = conv2(double(colorBand), double(my2), 'same');
% compute magnitude for each pixel in segmented region R
% magnitude1 = zeros(sum(mask(:)), 1);
% magnitude1 = double(magnitude1);
% for i = 1:length(R)
%     % determine x,y coordinates of segmented region R
%     x = R(i,1);
%     y = R(i,2);
%     % check boundaries
%     [rows cols] = size(y1);
%     [rows2 cols2] = size(y2);
%     if x < rows && y < cols && x < rows2 && y < cols2
%     % find magnitude by sqrt(Vx,y^2+Hx,y^2)
%         magnitude(i,1) = sqrt(y1(x,y).*y1(x,y) + y2(x,y).*y2(x,y));
%     end
%     
%     [rows cols] = size(y3);
%     [rows2 cols2] = size(y4);
%     if x < rows && y < cols && x < rows2 && y < cols2
%     % do the same for second mask
%         magnitude(i,1) = magnitude(i,1) + sqrt(y3(x,y).*y3(x,y) + y4(x,y).*y4(x,y));
%     end
% end

mask = logical(mask);
magnitude1 = sqrt(y1(mask).*y1(mask) + y2(mask).*y2(mask));
magnitude2 = sqrt(y3(mask).*y3(mask) + y4(mask).*y4(mask));

output = magnitude1+magnitude2;



